import React, { useState, useEffect } from 'react';
import ReactEChartsCore from 'echarts-for-react/lib/core';
import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { BarChart } from 'echarts/charts';
import { ToolboxComponent, TooltipComponent, GridComponent, DataZoomComponent } from 'echarts/components';
import { loc, to_float, for_obj, obj_empty } from 'sui';

echarts.use([BarChart, ToolboxComponent, TooltipComponent, GridComponent, DataZoomComponent, CanvasRenderer]);

const ChartS = ({ cur, tp, title, gc, diff=0.5 }) => {
    const [option, setOption] = useState();
    const [v_max, vMax] = useState();
    const [v_min, vMin] = useState();
    const [v_num, vNum] = useState();
    const [v_avg, vAvg] = useState();

    useEffect(() => {
        if (obj_empty(cur) || obj_empty(cur[tp])) {
            return;
        }

        const b_data = cur[tp]["v"];
        const b_max = cur[tp]["max"];
        const b_min = cur[tp]["min"];

        const getVal = (v) => v;

        const max = getVal(b_max);
        const min = getVal(b_min);

        const index_data = [];
        let s = min;

        while (true) {
            let e = s + diff;
            if (e > max) {
                e = max;
            }

            index_data.push(s)

            s = e;

            if (s >= max) {
                break;
            }
        }

        if (isNaN(max)) {
            vMax("");
        } else {
            vMax(max);
        }

        if (isNaN(min)) {
            vMin("");
        } else {
            vMin(min);
        }

        const map_data = {};

        b_data.forEach(d => {
            const d_v = getVal(d);

            const f = index_data.find(t => d_v >= t && d_v < t + diff);
            if (f || f === 0) {
                const k = `${f}`;
                if (map_data[k]) {
                    map_data[k] += 1;
                } else {
                    map_data[k] = 1;
                }
            }
        });

        const data_val = [];
        let all = 0;
        let num = 0;

        for_obj(map_data, (k, v) => {
            const tmp = to_float(k);

            all += tmp;
            num += v;

            data_val.push([tmp, v]);
        });

        vNum(num);

        let t_avg = all / data_val.length;

        if (isNaN(t_avg)) {
            t_avg = "";
        } else {
            t_avg = t_avg.toFixed(2);
        }

        vAvg(t_avg);

        data_val.sort((a, b) => a[0] > b[0] ? 1: -1);

        data_val.forEach(d => {
            const a = d[0];
            const b = a + diff;

            d[0] = `${a.toFixed(1)}-${b.toFixed(1)}`;
        });

        const data = [{
            type: 'bar',
            barWidth: 30,
            data: data_val,
        }];

        const opt = {
            toolbox: {
                feature: {
                    saveAsImage: {
                        show: false,
                    }
                }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow',
                },
                formatter: function(para) {
                    const d = para[0];
                    if (!d.value) {
                        return "";
                    }

                    return d.value[0] + '<br/>' + d.value[1];
                }
            },
            xAxis: {
                type: 'category',
            },
            yAxis: {
                type: 'value',
            },
            label: {
                show: true,
                position: "top",
            },
            dataZoom: [
                {
                    type: 'slider',
                    height: 20,
                    start: 0,
                    end: 100
                },
            ],
            series: data,
        };

        setOption(opt);
    }, [cur, tp, gc, diff]);

    if (obj_empty(cur)) {
        return null;
    }

    if (obj_empty(option)) {
        return null;
    }

    return (
        <div className="flex flex-col">
            <div className="ml-2 mt-2 text-base flex justify-center">
                {title}
                <span className="ml-8">{loc("l_595")}<span className="ml-2">{v_num}</span></span>
                <span className="ml-4">{loc("l_646")}<span className="ml-2">{v_max}</span></span>
                <span className="ml-4">{loc("l_696")}<span className="ml-2">{v_min}</span></span>
                <span className="ml-4">{loc("l_897")}<span className="ml-2">{v_avg}</span></span>
            </div>
            <ReactEChartsCore echarts={echarts} option={option} style={{ height: '300px' }}/>
        </div>
    );
};


export {ChartS};
